<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="4" :sm="24">
              <a-form-item label="查找学校名称">
                <a-select
                  v-model="queryParam.school_id"
                  show-search
                  placeholder="请选择学校名称"
                  option-filter-prop="children"
                  :filter-option="filterOption"
                >
                  <a-select-option :value="item.id" v-for="(item) in roleList" :key="item.id">
                      {{item.name}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24" class="item">
              <a-form-item label="查找学校标签">
                <a-tree-select
                  v-model="test"
                  :tree-data="treeData"
                  tree-checkable
                  @change="changeSelect"
                  :show-checked-strategy="SHOW_PARENT"
                  placeholder="请选择学校标签"
                />
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-form-item label="查找任务状态">
                <a-select v-model="queryParam.status" placeholder="请选择" default-value="1">
                  <a-select-option value="1">未完成</a-select-option>
                  <a-select-option value="2">完成</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
              <a-col :md="4" :sm="24">
              <a-form-item label="查找任务名称">
                <a-select
                  v-model="queryParam.task_id"
                  show-search
                  placeholder="请选择任务名称"
                  option-filter-prop="children"
                  :filter-option="filterOption"
                >
                  <a-select-option :value="item.id" v-for="(item) in labelList" :key="item.id">
                      {{item.task_name}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <s-table
        ref="table"
        size="default"
        :rowKey="(record,index)=>{return index}"
        :columns="columns"
        :data="loadData"
        showPagination="auto"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>

        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)" v-action:schoolTask_wacth2>查看</a>
            <a-divider type="vertical" v-if="record.status !== '1'"/>
            <a-popconfirm
             v-if="record.status !== '1'"
              title="确定驳回吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="confirm(record)"
              @cancel="cancel(record)"
            >
              <a>驳回</a>
            </a-popconfirm>
          </template>
        </span>
      </s-table>

      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
      />

        <updata-form
        ref="createModal"
        :visible="updata"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleUpdataCancel"
        @ok="handleUpdataOk"
      />
      <step-by-step-modal ref="modal" @ok="handleOk"/>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { TreeSelect } from 'ant-design-vue';
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { GetAllSchoolTask, UpdataTaskListOne, DelTaskListOne, getSchoolList, GetTaskListOne, GetLabelList, DelRole } from '../../../api/school'

import StepByStepModal from './modules/StepByStepModal'
import CreateForm from './modules/CreateForm'
import UpdataForm from './modules/UpdataForm'

const columns = [
  {
    title: '编号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '学校名称',
    dataIndex: 'schoolname'
  },
  {
    title: '任务名称',
    dataIndex: 'taskname',
  },
  {
    title: '截止时间',
    dataIndex: 'endtime',
  },
  {
    title: '任务状态名称',
    dataIndex: 'statusname'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '120px',
    scopedSlots: { customRender: 'action' }
  },
]
const treeData = []
export default {
  name: 'schoolTask',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    StepByStepModal,
    UpdataForm
  },
  data () {
    this.columns = columns
    return {
      test: undefined,
      SHOW_PARENT,
      value: '',
      treeData,
      // 学校标签
      labelSchool: [],
      // 任务列表
      roleList: [],
      labelList: [],
      index: 0,
      // 动态表单数据
      dataList: [],
      // updata model
      updata: false,
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam, {user_id: localStorage.getItem('users_id'), role_type: localStorage.getItem('role_type'), category_id: this.value})
        console.log('loadData request parameters:', requestParameters)
        return GetAllSchoolTask(requestParameters)
          .then(res => {
            return res.data
          })
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  created() {
    // 调用方法获取任务列表
    this.UsersGetRoLeList ()
    // 调用方法获取标签列表
    this.UsergetDepartmentList()
    // 调用方法获取学校标签列表
    this.UsersGetLabelList()
  },
  methods: {
    changeSelect(values, label, extra) {
      if( extra.allCheckedNodes ) {
        console.log(values)
        const children = extra.allCheckedNodes.map(item => {
          return item.children && item.children.map(item => {
          return item.node.key
          })
        })
        children.push(values)
        this.value = children
      }
    },
    // 获取学校标签列表
    UsersGetLabelList () {
      GetLabelList().then(res => {
        console.log('-------------获取学校标签列表------------', res)
        const result = res.data.data.map(item => {
          return {
            title: item.name,
            key: item.id,
            value: item.id,
            children: item.children.map(item => {
              return {
                title: item.name,
                key: item.id,
                value: item.id,
              }
            })
          }
        })
        console.log(result)
        this.treeData = result
      })
    },
    // 获取学校列表
    UsersGetRoLeList () {
      getSchoolList().then(res => {
        console.log('-------------获取学校列表------------', res)
        this.roleList = res.data.data
      })
    },
    // 获取标签列表
    UsergetDepartmentList () {
      GetTaskListOne().then(res => {
        console.log('-------------获取任务列表------------', res)
        this.labelList = res.data.data
      })
    },
    // 获取数据
    getdata(value) {
      this.dataList = value

    },
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleEdit (record) {
      console.log('----------------this.record-----------', record)
      this.schoolId = record.school_id
      const value = {
        id: record.task_id,
        forms: record.forms,
        schoolId: record.school_id
      }
      this.$router.push({
        name: 'taskdataIndex',
        path: '/task/taskdata/index',
        query: {data: JSON.stringify(value)}
      })
      console.log('----------------this.schoolId-----------', value)
    },
    // 查看学校信息
    handleWatch (record) {
      this.updata = true
      this.mdl = { ...record }
    },
    // 删除
    confirm(e) {
      const form = this.$refs.createModal.form
      console.log(e);
      DelRole({id: e.id, status: e.status}).then(res => {
        // 重置表单数据
        form.resetFields()
        // 刷新表格
        this.$refs.table.refresh()
        this.$message.success('已驳回');
      }).catch(error => {
        console.log('-------------error------------', error)
      })
    },
    cancel(e) {
      console.log(e);
      this.$message.error('已取消');
    },
    // 查看
    handleUpdataCancel() {
      this.updata = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleUpdataOk() {},
    // 创建
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          if (values.id > 0) {
            // 修改 e.g.
            new Promise((resolve, reject) => {
              UpdataTaskListOne(values).then(res => {
                resolve()
              })
            }).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success('修改成功')
            }).catch(error => {
              this.$message.info('该用户名已存在')
              this.confirmLoading = false
            })
          } else {
            // 新增
            new Promise((resolve, reject) => {
              AddUser(values).then(res => {
                if(res.ret === 200) {
                  resolve()
                }else{
                  reject()
                }
              })
            }).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success('新增成功')
            }).catch(error => {
              this.$message.info('该用户名已存在')
              this.confirmLoading = false
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    // 显示修改密码窗口
    handleSub (record) {
      this.$router.push({
        name: 'UpdataForm',
        path: '/task/UpdataForm',
        query: {data: JSON.stringify(record)}
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date())
      }
    },
    // 重置
    reset () {
      const form = this.$refs.createModal.form
      this.queryParam = {}
      this.value = ''
      this.test = undefined
        // 重置表单数据
      form.resetFields()
      // 刷新表格
      this.$refs.table.refresh()
    },
    // 搜素模糊查询
    filterOption(input, option) {
      return (
    option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    }
  }
}
</script>
<style scoped>
.item{
  position: relative;
  z-index: 99;
}
</style>
